import React, { Component } from 'react'
import './index.css';
import PubSub from 'pubsub-js';

export default class Footer extends Component {
  constructor (props) {
    super(props);
    //用来存储事件和监听函数之间的关系
    this.eventMap = {};
  }
  //1.注册事件监听器
  // on(type, handler) {
  //   if(!(handler instanceof Function))  {
  //     throw new Error('请重新上传参数');
  //   }
  //   // 判断type事件对应的队列是否存在
  //   if(!this.eventMap[type]) {
  //     this.eventMap[type] = [];
  //     console.log('事件注册成功');
  //   } else {
  //     this.eventMap[type].push(handler);
  //   }
  // }

  // //2.发布
  // emit(type, params) {
  //   if (this.eventMap[type]) {
  //     this.eventMap[type].forEach((handler, index) => {
  //       handler(params);
  //     });
  //     console.log('发布成功');
  //   }
  // }

  // 3.解除绑定
  // off(type, handler) {
  //   if (this.eventMap[type]) {
  //     this.eventMap[type].splice(this.eventMap[type].indexOf(handler) >>> 0, 1);
  //   }
  //   console.log('事件解除成功');
  // }

  CheckAllTodo = (event) => {
      const {target} = event;
      this.props.CheckAllTodo(target.checked);
  }
  clearDoneTodos = () => {
      this.props.clearDoneTodos();
  }
  componentDidMount () {
     console.log(this); // this指向当前Footer组件
     this.myPubSub = PubSub.subscribe('MYINPUT', (msg, data) => {
     console.log(msg);  // MYINPUT
     console.log('接收到发布的消息了',data); // 文本框输入的值
    }); //订阅消息
  }
  componentWillUnmount () {
    PubSub.unsubscribe(this.myPubSub);
    console.log('取消订阅了');
  }
  render() {
    const {todos} = this.props; 
    //已完成--计数
    const doneCount = todos.reduce((pre,todo) => {
        return pre + (todo.done ? 1: 0);
    },0);
    //总数
    const total = todos.length;
    return (
      <div className='todo-footer'>
          <label>
              <input type="checkbox" checked={doneCount === total && total !== 0 ? true: false }  onChange={this.CheckAllTodo} />
              <span>
              <span>已完成{doneCount}</span> /全部{total}
          </span>
          </label>
          <button className='btn btn-danger' onClick={this.clearDoneTodos}>清除已完成任务</button>
      </div>
    )
  }
}
//实例化
// const myEvenet = new Footer();

// const testHandler = function(params) {
//   console.log(`test事件被触发了,testHandler接受到的参数是${params}`);
// }
// // 监听test事件
// myEvenet.on('test', testHandler);
// myEvenet.emit('test', testHandler('newState'));
// myEvenet.off('test',testHandler);
